using System.Threading.Tasks;
using GetKlient.Models;
using Microsoft.EntityFrameworkCore;

namespace GetKlient.Services
{
    public class OpenInsService
    {
        private readonly PFlibDbContext _dbContext;

        public OpenInsService(PFlibDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task InsertOpenIns(string openid, string title)
        {
            try
            {
                var openIns = new Models.OpenIns
                {
                    OpenID = openid,
                    Title = title
                };
                _dbContext.OpenIns.Add(openIns);
                await _dbContext.SaveChangesAsync();
            }
            catch (System.Exception ex)
            {
                throw new System.Exception($"插入 OpenIns 时出错：{ex.Message}");
            }
        }

        public async Task<bool> TableExists()
        {
            try
            {
                var result = await _dbContext.Database.ExecuteSqlRawAsync("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'OpenIns'");
                return result > 0;
            }
            catch (System.Exception ex)
            {
                throw new System.Exception($"判断 OpenIns 表是否存在时出错：{ex.Message}");
            }
        }

        public async Task CreateTable()
        {
            try
            {
                await _dbContext.Database.ExecuteSqlRawAsync("CREATE TABLE OpenIns (id INT IDENTITY(1,1) PRIMARY KEY, openid VARCHAR(255), title VARCHAR(255))");
            }
            catch (System.Exception ex)
            {
                throw new System.Exception($"创建 OpenIns 表时出错：{ex.Message}");
            }
        }
    }
}